import React, { Component } from 'react';
import { Table, Tooltip, Helper, Dialog } from '@knownsec/react-component';
import { localScanColumns, scanHttpParams, scanPingParams } from '../columns';
import { getScanResult } from '~/API';
import s from './style.module.less';
import moment from 'moment';
import RuleTable from '@/components/RuleTable';
import EmptyData from '../../../../components/EmptyData';
const STATUS=['未知','正常','异常']
const STATUS_C=['#7f7e7d','#11ab4e','#f04038']
const info = localStorage.info ? JSON.parse(localStorage.info).modules : [];
class Availability extends Component {
  constructor(props) {
    super(props);
    this.state = {
      showDialog: false,
      currentDetail: { pingObj: {} },
      cloudsList: [],
      localList: [],
      loading: false,
    };
    this.columns = [
      {
        key: 'created_at',
        dataIndex: 'created_at',
        title: '监测时间',
        render: (value) => {
          const time = value ? moment(value).format('YYYY-MM-DD HH:mm:ss') : '-';
          return (
            <Tooltip
              overlay={
                <>
                  <p>监测时间：{time}</p>
                </>
              }
              placement="topLeft"
            >
              <div className={s.textellipsis}>{time}</div>
            </Tooltip>
          );
        },
      },
      {
        key: 'area',
        dataIndex: 'area',
        title: '监测点',
        render: (value) => {
          const name = value || '-';
          return (
            <Tooltip
              overlay={
                <>
                  <p>监测点：{name}</p>
                </>
              }
              placement="topLeft"
            >
              <div className={s.textellipsis}>{name}</div>
            </Tooltip>
          );
        },
      },
      {
        key: 'presp_time',
        dataIndex: 'presp_time',
        title: 'Ping响应时间',
        render: (value) => ( value !== '-' ? value + 'ms' : '-'),
      },
      {
        key: 'resp_time',
        dataIndex: 'resp_time',
        title: 'HTTP响应时间/状态码',
        className: s.w200,
        render: (value, row) => {
          const { status_code } = row;
          const time = value !== '-' ? value + 'ms' : '-';
          const status = status_code !== '-' ? status_code : '-';
          return `${time} / ${status}`;
        },
      },
      {
        key: 'dns_time',
        dataIndex: 'dns_time',
        title: '域名解析速度',
        render: (value) => ( value !== '-' ? value + 'ms' : '-'),
      },
      {
        key: 'download_speed',
        dataIndex: 'download_speed',
        title: '页面读取速度',
        render: (value) => ( value !== '-' ? value + 'ms' : '-'),
      },
      {
        key: 'normal_status',
        dataIndex: 'normal_status',
        title: (
          <div>
            可用性状态
            <Helper
              placement="top"
              overlay="按HTTP响应状态码判定，检测处于200-299即可用性正常"
              className="paddingHelp"
            ></Helper>
          </div>
        ),
        render: (value) => {
          const STATUS = ['未知', '正常', '异常'];
          const STATUS_C = ['#7f7e7d', '#11ab4e', '#f04038'];
          if (!value) {
            return '-';
          } else {
            return <span style={{ color: STATUS_C[value] }}>{STATUS[value]}</span>;
          }
        },
      },
      {
        key: 'option',
        dataIndex: 'option',
        title: '操作',
        render: (value, _data) => (
          <>
            <span
              className={s.linkStyle}
              onClick={() => {
                this.setVal(_data, true);
              }}
            >
              详情
            </span>
          </>
        ),
      },
    ];
  }
  componentDidMount() {
    this.getData();
  }
  getData() {
    if (this.props?.fetchable === 'fail') return false;
    this.setState({ loading: true });
    getScanResult({ id: this.props.targetId, type: 'availability' })
      .then((res) => {
        if (res.status === 'success') {
          const clouds = res.data?.clouds || [];
          let httpdata = [],
            pingdata = [];
          clouds.forEach((c) => {
            const pings = c?.cloud?.detail_ping || [];
            let httpd = c?.cloud?.detail_http || [];
            httpd.map((item) => {
              pings.map((p) => {
                if (item.area === p.area) {
                  item.presp_time = p.resp_time;
                  item.created_at = c.created_at
                    ? moment(c.created_at).format('YYYY-MM-DD HH:mm:ss')
                    : '-';
                  p.created_at = item.created_at;
                  item.pingObj = p;
                }
              });
            });
            if (httpd.length) {
              httpdata = httpdata.concat(httpd);
            }
          });
          console.log('[ res.data?.details ]-136', res.data?.details);
          console.log('[  ]-159', httpdata);
          this.setState({
            cloudsList: this.props?.avaCloud ? httpdata : [],
            localList: res.data?.details || [],
            loading: false,
          });
        } else {
          this.setState({ cloudsList: [], localList: [], loading: false });
        }
      })
      .catch((_) => {
        this.setState({ cloudsList: [], localList: [], loading: false });
      });
  }
  setVal(detail, value) {
    console.log('[ detail, value ]-145', detail, value);
    this.setState({
      showDialog: value,
      currentDetail: detail,
    });
  }
  header(header) {
    let hObj = {};
    try {
      hObj = JSON.parse(header);
    } catch {
      hObj = {};
    }
    if (Object.entries(hObj).length > 0) {
      return Object.entries(hObj).map(([k, v]) => {
        return (
          <p className={s.headerP}>
            {k}:{v}
          </p>
        );
      });
    } else {
      return '暂无';
    }
  }
  closeDailog() {
    this.setState({ showDialog: false });
  }
  render() {
    const pingObj = this.state.currentDetail?.pingObj;
    const currentDetail = this.state.currentDetail;
    return (
      <div className={s.wangava}>
        <div className={s.title}>
          本地监测
          <Helper
            placement="top"
            overlay="展示最近5次本地可用性监测数据"
            className="paddingHelp"
          ></Helper>
        </div>
        <Table
          columns={localScanColumns}
          tableLoading={this.state.loading}
          loadingLabel=""
          empty={this.props?.fetchable === 'fail' && <EmptyData text="未开启该监测项" />}
          data={this.state.localList}
        ></Table>
        <div className={s.title}>
          云端监测
          <Helper
            placement="top"
            overlay="展示最近1次云端可用性监测数据"
            className="paddingHelp"
          ></Helper>
        </div>
        {info.includes('cloud') ? (
          <Table
            columns={this.columns}
            tableLoading={this.state.loading}
            loadingLabel=""
            empty={!this.props?.avaCloud && <EmptyData text="未开启该监测项" />}
            data={this.state.cloudsList}
          ></Table>
        ) : (
          <RuleTable columns={this.columns} data={this.state.cloudsList}></RuleTable>
        )}

        <Dialog
          className="wangDialog"
          title="监测详情"
          closable={true}
          cancelText=""
          confirmText="确定"
          onsubmit={() => this.closeDailog()}
          onhide={() => this.closeDailog()}
          visible={this.state.showDialog}
        >
          <div className={s.scandialog}>
            <div className={s.title}>HTTP监测</div>
            <div className={s.itemflex}>
              <div>
                <p>
                  监测点: <span>{currentDetail?.area || '-'}</span>
                </p>
                <p>
                  监测时间:
                  <span>
                    {currentDetail?.created_at
                      ? moment(currentDetail?.created_at).format('YYYY-MM-DD HH:mm:ss')
                      : '-'}
                  </span>
                </p>
                <p>
                  响应服务器IP: <span>{currentDetail?.ip || '-'}</span>
                </p>
                <p>
                  HTTP响应长度:{' '}
                  <span>
                    {currentDetail?.content_len !== '-' ? currentDetail?.content_len + 'B' : '-'}
                  </span>
                </p>
                <p>
                  响应状态码:{' '}
                  <span>
                    {currentDetail?.status_code !== '-' ? currentDetail?.status_code : '-'}
                  </span>
                </p>
                <p>
                  域名解析速度:{' '}
                  <span>
                    {currentDetail?.dns_time !== '-' ? currentDetail?.dns_time + 'ms' : '-'}
                  </span>
                </p>
                <p>
                  页面读取速度:{' '}
                  <span>
                    {currentDetail?.download_speed !== '-'
                      ? currentDetail?.download_speed + 'ms'
                      : '-'}
                  </span>
                </p>
                <p>
                  服务器连接耗时:{' '}
                  <span>
                    {currentDetail?.ssl_shake_time !== '-'
                      ? currentDetail?.ssl_shake_time + 'ms'
                      : '-'}
                  </span>
                </p>
                <p>
                  服务器响应耗时:{' '}
                  <span>
                    {currentDetail?.response_time !== '-'
                      ? currentDetail?.response_time + 'ms'
                      : '-'}
                  </span>
                </p>
                <p>
                  内容下载时间:{' '}
                  <span>
                    {currentDetail?.download_time !== '-'
                      ? currentDetail?.download_time + 'ms'
                      : '-'}
                  </span>
                </p>
                <p>
                  总响应时间:{' '}
                  <span>
                    {currentDetail?.resp_time !== '-' ? currentDetail?.resp_time + 'ms' : '-'}
                  </span>
                </p>
                <p>
                    监测结果: <span style={{color:STATUS_C[this.state.currentDetail?.normal_status]}}>{STATUS[this.state.currentDetail?.normal_status]}</span>
                  </p>
              </div>
              <div>{this.header(currentDetail?.header)}</div>
            </div>
            <div className={s.title}>Ping监测</div>
            <div className={s.itemflex}>
              <div>
                <p>
                  监测点: <span>{pingObj?.area || '-'}</span>
                </p>
                <p>
                  监测时间:{' '}
                  <span>
                    {currentDetail.created_at
                      ? moment(currentDetail.created_at).format('YYYY-MM-DD HH:mm:ss')
                      : '-'}
                  </span>
                </p>
                <p>
                  响应主机IP: <span>{pingObj?.ip || '-'}</span>
                </p>
                <p>
                  响应时间:{' '}
                  <span>{pingObj?.resp_time !== '-' ? pingObj?.resp_time + 'ms' : '-'}</span>
                </p>
                <p>
                  发送包数量:{' '}
                  <span>
                    {pingObj?.packets_transmitted !== '-'
                      ? pingObj?.packets_transmitted + '个'
                      : '-'}
                  </span>
                </p>
                <p>
                  接收包数量:{' '}
                  <span>
                    {pingObj?.packets_received !== '-' ? pingObj?.packets_received + '个' : '-'}
                  </span>
                </p>
                <p>
                  丢包率:{' '}
                  <span>{pingObj.loss_rate !== '-' ? pingObj?.loss_rate * 100 + '%' : '-'}</span>
                </p>
                {/* {pingObj.has_error ? (
                  <p>
                    监测结果: <span className={s.error}>异常</span>
                  </p>
                ) : (
                  <p>
                    监测结果: <span className={s.safe}>正常</span>
                  </p>
                )} */}
              </div>
            </div>
          </div>
        </Dialog>
      </div>
    );
  }
}

export default Availability;
